﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using MSExcel = Microsoft.Office.Interop.Excel;
using System.Drawing;
using KPWeb.Data;
using System.Data;
using KPWeb.Function;
using System.Reflection;
using KPWeb.Class;
using KPWeb.Kontrolki;
using Microsoft.Reporting.WebForms;




//using Spire.XlS; 

namespace KPWeb
{
    public partial class Raporty : KPPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.HyperLink1.NavigateUrl = "javascript:var w=window.open('Reports/RaportyStrona.aspx?P=place','_blank'); w.focus();";
            this.HyperLink2.NavigateUrl = "javascript:var w=window.open('Reports/RaportyStrona.aspx?P=ka','_blank'); w.focus();";
          
            this.ListaObecnosc.NazwaRaportu = "Test";
        }

        protected void ExcelListy_Click(object sender, EventArgs e)
        {
            string fileName ="limity.xls";

            string filePath = Server.MapPath("~/EXCEL/limity.xls");

            Response.Clear();



            Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
   
            Response.ContentType = "application/octet-stream";

            Response.WriteFile(filePath);

            Response.Flush();

            Response.End(); 
 

        }
        protected void ExcelChart_Click(object sender, EventArgs e)
        {
          //  const string fileName = "~/TESTY/Book1.xlsx";
         
                const string topLeft = "A1";
                const string bottomRight = "A4";
                const string graphTitle = "Graph Title11";
                const string xAxis = "Time11";
                const string yAxis = "Value11";
                string fileName = "Book1.xlsx";

                string filePath = Server.MapPath("~/TESTY/Book1.xlsx");

	            // Open Excel and get first worksheet.
	            var application = new MSExcel.Application();
	            var workbook = application.Workbooks.Open(filePath);
	            var worksheet = workbook.Worksheets[1] as
	                Microsoft.Office.Interop.Excel.Worksheet;

	            // Add chart.
	            var charts = worksheet.ChartObjects() as
	                Microsoft.Office.Interop.Excel.ChartObjects;
	            var chartObject = charts.Add(60, 10, 300, 300) as
	                Microsoft.Office.Interop.Excel.ChartObject;
	            var chart = chartObject.Chart;

	            // Set chart range.
	            var range = worksheet.get_Range(topLeft, bottomRight);
	            chart.SetSourceData(range);

	            // Set chart properties.
	            chart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;
	            chart.ChartWizard(Source: range,
	                Title: graphTitle,
	                CategoryTitle: xAxis,
	                ValueTitle: yAxis);

	            // Save.
	     workbook.Save();
   //utworzył w folderze  oBRAZY
 

        }

        protected void ExcelSave_Click(object sender, EventArgs e)
        {
            MSExcel.Application xlApp;
            MSExcel.Workbook xlWorkBook;
            MSExcel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            string filePath = Server.MapPath("~/TESTY/Book1.xlsx");


            xlApp = new MSExcel.Application();
            xlWorkBook = xlApp.Workbooks.Add(misValue);

            xlWorkSheet = (MSExcel.Worksheet)xlWorkBook.Sheets["Arkusz1"];
            xlWorkSheet.Name = "Exported Data";

            xlWorkSheet.Cells[1, 1] = "Demo";
            xlWorkSheet = (MSExcel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            
            xlWorkBook.SaveAs(filePath, MSExcel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
                MSExcel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);

            xlWorkSheet = null;
            xlWorkBook = null;
            xlApp = null;
            GC.Collect();
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

        private void ExcelDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }

       protected void ExcelView_Click(object sender, System.EventArgs e)
        {

            int dlObecnosci = 37;
            int iAll = 0;
           int[][] formatRow=new int[3][];
           formatRow[0]=new int[2] {1,12};
           formatRow[1]=new int[2] {4,125};
           formatRow[2]=new int[2] {5,10};
         //   string temp = "";
           vKP_Swieta[] ListaSwiat = Kalendarz.GetSwieta(2013, 1);
         
            int lastDayMonth = FunctionGlobal.IleDniMiesiac(2013, 1);
           
           
           MSExcel.Application excelApp = new MSExcel.Application();
            string filePath = Server.MapPath("~/EXCEL/SzObecnosci.xls");

          
        

            //MSExcel.Workbook excelWorkbook = excelApp.Workbooks.Open(filePath,
            //        0, true, 5, "", "", false, MSExcel.XlPlatform.xlWindows, "",true, false, 0, true, false, false);

            //MSExcel.Sheets excelSheets = excelWorkbook.Worksheets;

            //string currentSheet = "Arkusz1";
            //MSExcel.Worksheet excelWorksheet = (MSExcel.Worksheet)excelSheets.get_Item(currentSheet);
            //MSExcel.Range excelCell = (MSExcel.Range)excelWorksheet.get_Range("A1", "A1");

////////////////////////////////////////////////
            

            //int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            //Range rng = excelApp.get_Range("A1", "J1");
            //rng.Value = intArray;

            //nowy otwórz
            //  MSExcel.Workbook newWorkbook = excelApp.Workbooks.Add();
            //istniejacy otwórz
            MSExcel.Workbook  excelWorkbook = excelApp.Workbooks.Open(filePath,
                    0, true, 5, "", "", false, MSExcel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

            //Opis parametrów funkcji   //msdn.microsoft.com/en-us/library/bb179167%28v=office.12%29.aspx
           //  WorkBooks.open(string Filename, object UpdateLinks, object ReadOnly, object Format, object Password,
           //object WriteResPassword, object ReadOnlyRecommend, object Origin, object Delimiter,
           //object Editable, object Notify, object Converter, object AddToMru, object Local, object CorruptLoad )

            MSExcel.Sheets excelSheets = excelWorkbook.Worksheets;

            string currentSheet = "Obecnosci";
            MSExcel.Worksheet excelWorksheet = (MSExcel.Worksheet)excelSheets.get_Item(currentSheet);

            MSExcel.Range excelCell = (MSExcel.Range)excelWorksheet.get_Range("F2", "F2");
            MSExcel.Range excelCellTarget;
            excelCell.Value= "Dział Informatyki";

       //    excelCell = (MSExcel.Range)excelWorksheet.get_Range("C4", "C4");
    
      //      excelCell.Value = "Leon Iksinski";


            DateTime d = new DateTime(); 
            for (int i = 0; i < lastDayMonth; i++)
               
            {
                d = new DateTime(2013, 1, i+1);
                if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
                {
                    excelCell = (MSExcel.Range)excelWorksheet.get_Range("C" + (i + 6).ToString(), "L" + (i + 6).ToString());

                    excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;
                    excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;
                }
            }

            foreach (vKP_Swieta sw in ListaSwiat)
            {
                excelCell = (MSExcel.Range)excelWorksheet.get_Range("C" + (sw.day + 5).ToString(), "L" + (sw.day + 5).ToString());

                excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;
                excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;
            }
            for (int i = lastDayMonth; i <31 ; i++)
            {
                d = new DateTime(2013, 1, i + 1);
              
                    excelCell = (MSExcel.Range)excelWorksheet.get_Range("C" + (i + 6).ToString(), "L" + (i + 6).ToString());

                    excelCell.Borders.LineStyle = MSExcel.XlLineStyle.xlContinuous;
                    excelCell.Borders[MSExcel.XlBordersIndex.xlDiagonalUp].LineStyle = MSExcel.XlLineStyle.xlContinuous;
            
            }


            iAll += dlObecnosci;
            excelCell = (MSExcel.Range)excelWorksheet.get_Range("A1", "L" + (dlObecnosci).ToString());
            excelCellTarget = (MSExcel.Range)excelWorksheet.get_Range("A" + (iAll + 1).ToString(), "L" + (iAll + dlObecnosci).ToString());


          //  excelCell.Copy(Type.Missing);
          //  excelCellTarget.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteFormulas,
          //      Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);

            excelCell.Copy(excelCellTarget);
           for(int i=0;i<formatRow.Length;i++)
                {
                    ((MSExcel.Range)excelWorksheet.Rows[iAll + formatRow[i][0], Missing.Value]).RowHeight = formatRow[i][1];
       
               }

           excelCell = (MSExcel.Range)excelWorksheet.get_Range("B4", Type.Missing);

            Model  model = new Model();
           //  IEnumerable< vKP_OsobyListaObecnosci> ListaObecnosci = this.mo
            foreach (vKP_OsobyListaObecnosci item in model.GetListaObecnosci("J2WUM"))
            {

                excelCell.Offset[0, item.PozycjaNaStronie].Value = item.NazwiskoImie;

              //  excelCell.Value = "DDDDDD";
            }
            excelApp.Visible = true;
        }
///////////////////


       protected void btnUrlop_Click(object sender, EventArgs e)
       {
        
           //RaportLinkButton org = e.Item.FindControl("OryginalRLB") as RaportLinkButton;
           RaportLinkButton rob = this.FindControl("urlopRLB") as RaportLinkButton;
           //string DokNr = (e.Item.FindControl("DokumentNr") as Label).Text;
           string paramD = "";
           string nazwaRap = "";

           try
           {
               nazwaRap = "~/Reports/WniosekUrlop.rdlc";
           //    rob.DodatkowePrametry = paramD;
               rob.NazwaRaportu = "?" + nazwaRap;
           }
           catch (Exception ex)
           {
               //throw new Exception(href + "/////" + ex.Message);
           }
       }

       //protected void urlopRLB_Click(object sender, EventArgs e)
       //{
       //    KPWeb.Function.Barcode.TextToBarCode = "019876549";
       //    //List<ReportDataSource> rds = new List<ReportDataSource>();
       //    //rds.Add(new ReportDataSource("DataSet1", Model.GetListaObecnosci(194)));
       //    //rds.Add(new ReportDataSource("DataSet2", KPWeb.Function.Barcode.GetBarcode()));    
       //    ReportDataSource rds=new ReportDataSource("DataSet1", KPWeb.Function.Barcode.GetBarcode());

       //    //List<Microsoft.Reporting.WebForms.ReportParameter> l = new List<ReportParameter>();
       //    //l.Add(new Microsoft.Reporting.WebForms.ReportParameter("P1", "XXXXXXXXXXX"));


       //    //Microsoft.Reporting.WebForms.LocalReport report = KPWeb.Reports.LocalReport.GenerujRaport("WniosekUrlop.rdlc", rds, l);
       //    Microsoft.Reporting.WebForms.LocalReport report = KPWeb.Reports.LocalReport.GenerujRaport("WniosekUrlopowy.rdlc", rds);
       //     //Microsoft.Reporting.WebForms.LocalReport report = KPWeb.Reports.LocalReport.GenerujRaport("WniosekOWypłatęŚwiadczeńŚwiątecznych.rdlc", rds, null);
       ////    KPWeb.Reports.LocalReport.Export(report, "Excel", "RankingNauczycieli.xls");
       //    KPWeb.Reports.LocalReport.Export(report, "PDF", "WniosekUrlopowy.pdf");
       //}
       protected void urlopRLB_Click(object sender, EventArgs e)
       {
           KPWeb.Function.Barcode.TextToBarCode = "019876549";
           KPWeb.Function.Barcode.IsVerticalTextToBarCode = true;
           List<ReportDataSource> rds = new List<ReportDataSource>();
           rds.Add(new ReportDataSource("DataSet1", KPWeb.Function.Barcode.GetBarcode()));
           KPWeb.Function.Barcode.IsVerticalTextToBarCode = false;
           rds.Add(new ReportDataSource("DataSet2", KPWeb.Function.Barcode.GetBarcode()));    
         

           List<Microsoft.Reporting.WebForms.ReportParameter> l = new List<ReportParameter>();
           l.Add(new Microsoft.Reporting.WebForms.ReportParameter("P1", KPWeb.Function.Barcode.TextToBarCode));


          //Microsoft.Reporting.WebForms.LocalReport report = KPWeb.Reports.LocalReport.GenerujRaport("WniosekUrlop.rdlc", rds, l);
          Microsoft.Reporting.WebForms.LocalReport report = KPWeb.Reports.LocalReport.GenerujRaport("WniosekUrlopowy.rdlc", rds,l);
           //    KPWeb.Reports.LocalReport.Export(report, "Excel", "RankingNauczycieli.xls");
           KPWeb.Reports.LocalReport.Export(report, "PDF", "WniosekUrlopowy.pdf");
       }

///////////////////
    }
}